import { getUserProfile, updataPhoto, updateUserProfile } from '@/store/actions/profile'
// import { RootState } from '@/types/store'
import { useInitialState } from '@/utils/hooks'
import { Button, List, DatePicker, NavBar, Popup, Toast, Dialog } from 'antd-mobile'
import classNames from 'classnames'
import { useRef, useState } from 'react'
// import { useEffect } from 'react'
import { useDispatch } from 'react-redux'
import { useHistory } from 'react-router-dom'
import EditInput from './EditInput'
import EditList from './EditList'
import moment from 'moment'
import styles from './index.module.scss'
import { logout } from '@/store/actions/login'
const Item = List.Item
const ProfileEdit = () => {
  type inputState = {
    type: '' | 'name' | 'intro'
    visible: boolean
  }
  type listState = {
    type: '' | 'gender' | 'photo'
    visible: boolean
  }
  const [showInput, setShowInput] = useState<inputState>({
    type: '',
    visible: false,
  })
  const [showLIst, setShowList] = useState<listState>({
    type: '',
    visible: false,
  })

  const [visible, setVisible] = useState(false)
  const history = useHistory()
  const dispatch = useDispatch()
  // const { profile } = useSelector((state: RootState) => state.profile)
  // useEffect(() => {
  //   dispatch(getUserProfile())
  // }, [dispatch])
  const { profile } = useInitialState(getUserProfile, 'profile')
  //关闭弹出层
  const hideInput = () => {
    setShowInput({
      type: '',
      visible: false,
    })
  }
  const hideList = () => {
    setShowList({
      type: '',
      visible: false,
    })
  }

  const fileRef = useRef<HTMLInputElement>(null)
  const onChangePhoto = (e: React.ChangeEvent<HTMLInputElement>) => {
    //拿到圖片的信息
    if (e.target.files) {
      //拿到圖片信息
      const files = e.target.files[0]
      //創建一個FormData對象
      const formData = new FormData()
      //給FormData對象添加圖片對象接口文檔對象名規定是photo值就是files
      formData.append('photo', files)
      dispatch(updataPhoto(formData))
      Toast.show({
        content: '修改成功',
        icon: 'success',
      })
      hideList()
    }
  }
  const onUpdata = async (key: string, value: string) => {
    console.log(key, value)
    if (key === 'photo') {
      console.log('需要修改頭像')
      fileRef.current?.click()

      return
    }
    await dispatch(
      updateUserProfile({
        [key]: value,
      })
    )
    Toast.show({
      content: '修改成功',
      icon: 'success',
    })
    hideInput()
    hideList()
  }

  return (
    <div className={styles.root}>
      <div className='content'>
        {/* 标题 */}
        <NavBar
          style={{
            '--border-bottom': '1px solid #F0F0F0',
          }}
          onBack={() => history.go(-1)}>
          个人信息
        </NavBar>

        <div className='wrapper'>
          {/* 列表 */}
          <List className='profile-list'>
            {/* 列表项 */}
            <Item
              extra={
                <span className='avatar-wrapper'>
                  <img width={24} height={24} src={profile.photo} alt='' />
                </span>
              }
              arrow
              onClick={() =>
                setShowList({
                  visible: true,
                  type: 'photo',
                })
              }>
              頭像
            </Item>
            <Item
              arrow
              extra={profile.name}
              onClick={() =>
                setShowInput({
                  type: 'name',
                  visible: true,
                })
              }>
              暱稱
            </Item>
            <Item
              arrow
              extra={<span className={classNames('intro', 'normal')}>{profile.intro}</span>}
              onClick={() =>
                setShowInput({
                  type: 'intro',
                  visible: true,
                })
              }>
              簡介
            </Item>
          </List>

          <List className='profile-list'>
            <Item
              arrow
              extra={profile.gender === 0 ? '男' : '女'}
              onClick={() =>
                setShowList({
                  visible: true,
                  type: 'gender',
                })
              }>
              性別
            </Item>
            <Item arrow extra={profile.birthday} onClick={() => setVisible(true)}>
              生日
            </Item>
          </List>

          <DatePicker
            visible={false}
            value={new Date()}
            title='選擇年月日'
            min={new Date(1900, 0, 1, 0, 0, 0)}
            max={new Date()}
          />
        </div>

        <div className='logout'>
          <Button
            className='btn'
            onClick={() => {
              Dialog.show({
                title: '溫馨提示',
                content: '你確定要退出嗎',
                closeOnAction: true,
                actions: [
                  [
                    {
                      key: 'cancel',
                      text: '取消',
                    },
                    {
                      key: 'delete',
                      text: '確定',
                      bold: true,
                      danger: true,
                      onClick() {
                        dispatch(logout())
                        history.push('/login')
                      },
                    },
                  ],
                ],
              })
            }}>
            退出登錄
          </Button>
        </div>
      </div>

      <Popup
        visible={showInput.visible}
        position='right'
        bodyStyle={{ minWidth: '100vw' }}
        destroyOnClose>
        <EditInput hideInput={hideInput} type={showInput.type} onUpdata={onUpdata}></EditInput>
      </Popup>

      <Popup visible={showLIst.visible} position='bottom' destroyOnClose onMaskClick={hideList}>
        <EditList hideList={hideList} type={showLIst.type} onUpdata={onUpdata}></EditList>
      </Popup>

      <DatePicker
        visible={visible}
        title='生日選擇'
        value={new Date(profile.birthday)}
        max={new Date()}
        min={new Date('1900-01-01')}
        onCancel={() => {
          setVisible(false)
        }}
        onConfirm={async value => {
          await onUpdata('birthday', moment(value).format('YYYY-MM-DD'))

          setVisible(false)
        }}></DatePicker>

      <input type='file' hidden ref={fileRef} onChange={onChangePhoto} />
    </div>
  )
}

export default ProfileEdit
